package luanluan.control.application 
{
	import flash.utils.Dictionary;
	import flash.utils.getQualifiedClassName;
	import luanluan.utils.ArrayUtils;
	
	/**
	 * 对象池
	 * @author luanluan
	 * @version	1.0.1 2011.11.18
	 */
	public class ObjectPool  
	{
		private var _objDic:Dictionary = new Dictionary();		//对象字典
		
		private var _numDic:Dictionary = new Dictionary();		//数量限制字典
		
		/**
		 * 设置缓存最大数量
		 * @param	className
		 * @param	num
		 */
		public function setMaxCacheNum(className:Class, num:Number):void
		{
			_numDic[className] = num;
		}
		
		/**
		 * 从对象池中取出对象
		 * @param	className
		 * @return
		 */
		public function getObject(className:Class):*
		{
			var obj:* = null;
			var list:Vector.<*> = _objDic[className];
			if (list && list.length)
			{
				obj = list.shift();
			}
			else
			{
				list = new Vector.<*>();
				obj = new className();
				_objDic[className] = list;
			}
			return obj;
		}
		
		/**
		 * 将对象放到对象池中
		 * @param	obj
		 */
		public function push(obj:*):void
		{
			var className:Class = obj.constructor as Class;
			var list:Vector.<*> = getList(className);
			var len:int = list.length;
			var num:int = _numDic[className];
			ArrayUtils.addElement(list, obj);
			while (list.length > num)
			{
				list.shift();
			}
		}
		
		/**
		 * 获取某类对象列表
		 * @param	className
		 * @return
		 */
		private function getList(className:Class):Vector.<*> 
		{
			if (!_objDic[className])
				_objDic[className] = new Vector.<*>();
			
			return _objDic[className];
		}
		
		private static var _instance:ObjectPool;
		
		public function ObjectPool(single:Single)
		{ 
			if ( !single )
				throw(new Error( "请使用静态getter获取单例引用" ) );
		} 
		
		public static function get instance():ObjectPool 
		{
			if(_instance == null)
			{
				_instance = new ObjectPool(new Single());
			}
			return _instance;
		}
	}
}
class Single{}